<?php
namespace app\query\controller;

use GuzzleHttp\Client;
use QL\QueryList;
use think\Db;
use think\facade\Cache;
class Index
{
    public function index()
    {

        $config = [
            'catalog_url'=>'https://www.bqg8.cc/4_4876/',//目录页面的网址
            'page_base_url'=>'https://www.bqg8.cc/4_4876/',//爬取具体页面的网址，去掉最后面相同的部分
            'id'=>'1001001',//每个小说的id都不相同
        ];

        if(Cache::has('html_1')){
            $html = Cache::get('html_1');
        }else{
            $client = new Client();
            $res = $client->request('GET', $config['catalog_url'], [
                'wd' => 'QueryList'
            ]);
            $html = (string)$res->getBody();
            Cache::set('html_1',$html);
        }


        $data = QueryList::html($html)->find('#list a')->map(function ($item){
            return $item->href;
        });
        $saveData = [];
        foreach ($data as $val){
            $saveData['article_id'] = $config['id'];
            $saveData['url'] = $config['page_base_url'].$val;
        }
        Db::name('xiaoshuo_data')->insert($saveData);
    }

    public function onePage(){
        $result = Db::name('xiaoshuo_data')->where('state','=','1')->find();
        $url = $result['url'];
        $client = new Client();
        $res = $client->request('GET', $url, [
            'wd' => 'QueryList'
        ]);
        $html = (string)$res->getBody();

        $title = QueryList::html($html)->find('h1')->text();
        $data = QueryList::html($html)->find('#content')->text();
        $pp = preg_replace("/(\&nbsp\;|　|\xc2\xa0)/", " ", strip_tags($data));
        Db::name(xiaoshuo_data)->where('id','=',$result['id'])->update(['state'=>2,'data'=>$data,'title'=>$title]);
    }

    public function delAllData(){

    }

}
